package edu.guet.server.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public  class JwtTool {

    private static final String SING = "GUET2024Summer";//加密字符串，仅服务器可见

    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        // 默认7天过期
        instance.add(Calendar.DATE, 7);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        // payload
        map.forEach(builder::withClaim);
        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));  // sign
        return token;
    }

    // 解析JWT
    public static DecodedJWT verify(String token) {
        try {
            DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            return decodedJWT;
        }catch (SignatureVerificationException e){
            throw new CustomizationException(ExceptionEnum.SIGNATURE_ERROR);
        }catch (TokenExpiredException e){
            throw new CustomizationException(ExceptionEnum.TOKEN_EXPIRED);
        }catch (AlgorithmMismatchException e){
            throw new CustomizationException(ExceptionEnum.ALGO_ERROR);
        }catch (Exception e){
            throw new CustomizationException(ExceptionEnum.TOKEN_ERROR);
        }
    }

    public static String getUsernameByToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getSubject();
        } catch (JWTVerificationException exception){
            // Invalid token
            exception.printStackTrace();
            return null;
        }
    }
    public static Map<String, String> parseToken(String token) {
        try {
            DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SING))  // 使用与生成 Token 时相同的密钥进行验证
                    .build()
                    .verify(token);

            Map<String, String> claims = new HashMap<>();
            jwt.getClaims().forEach((k, v) -> claims.put(k, v.asString()));

            return claims;
        } catch (JWTDecodeException exception){
            // Invalid signature/claims
            throw new RuntimeException("Failed to decode JWT token: " + exception.getMessage());
        }
    }
}
